﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ViewModel;
using Helper;

namespace IssueTracker.CustomControls
{
    public partial class issueList : UserControl
    {
        Issue currentItem = null;
        public MainWindow objMain = null;
        public ViewModel.Filter doFilter = new ViewModel.Filter();
        public List<Issue> result = null;
        public issueList()
        {
            InitializeComponent();
        }

        private void issueList_Resize(object sender, EventArgs e)
        {
            if (this.ParentForm.WindowState == FormWindowState.Minimized)
                return;
            splitContainerLeft.Width = this.Width / 2;
            splitContainerLeft.SplitterDistance = splitContainerLeft.Width / 2;
            splitContainerRight.Width = this.Width / 2;
            splitContainerRight.SplitterDistance = splitContainerRight.Width / 2;

        }

        private void issueList_Load(object sender, EventArgs e)
        {
            cmbItemPerPage.SelectedIndex = 0;
            lblItemCount.Text = "Displaying";
            lblItemCount2.Visible = true;
            cmbItemPerPage.Visible = true;

            objMain.AcceptButton = btnSearch;
        }
        private void LoadIssuesPage()
        {
            List<Issue> issuesOpen = new List<Issue>();
            List<Issue> issuesInProgress = new List<Issue>();
            List<Issue> issuesClosed = new List<Issue>();
            List<Issue> issuesRejected = new List<Issue>();
            Service.Issues.GetAllIssues(ref issuesOpen, ref issuesInProgress, ref issuesClosed, ref issuesRejected, Convert.ToInt32(cmbItemPerPage.Text));

            //open issues
            treeViewOpenIssues.Nodes.Clear();
            treeViewOpenIssues.Nodes.AddRange(GetTree(issuesOpen).ToArray());

            //in progress issues
            treeViewInProgressIssues.Nodes.Clear();
            treeViewInProgressIssues.Nodes.AddRange(GetTree(issuesInProgress).ToArray());

            //closed issues
            treeViewClosedIssues.Nodes.Clear();
            treeViewClosedIssues.Nodes.AddRange(GetTree(issuesClosed).ToArray());

            //rejected issues            
            treeViewRejectedIssues.Nodes.Clear();
            treeViewRejectedIssues.Nodes.AddRange(GetTree(issuesRejected).ToArray());
            if (ActiveSession.User.Role != Role.Admininstrator)
            {
                lblOpenIssues.Text = String.Format("Open Issues ({0})", issuesOpen.Count);
                lblInProgressIssues.Text = string.Format("In Progress Issues ({0})", issuesInProgress.Count);
                lblClosedIssues.Text = string.Format("Closed Issues ({0})", issuesClosed.Count);
                lblRejectedIssues.Text = string.Format("Rejected Issues ({0})", issuesRejected.Count);
            }

            //save to result for export
            result = new List<Issue>();
            result.AddRange(issuesOpen);
            result.AddRange(issuesInProgress);
            result.AddRange(issuesClosed);
            result.AddRange(issuesRejected);
        }

        private List<TreeNode> GetTree(List<Issue> list)
        {
            List<TreeNode> nodes = new List<TreeNode>();
            if (ActiveSession.User.Role == Role.Admininstrator)
            {
                var shops = list.SelectMany(x => x.Assignee).ToList().Distinct().ToList();
                var shopIds = shops.OrderBy(x => x.Name).Select(x => x.ID).Distinct().ToList();
                foreach (var item in shopIds)
                {
                    TreeNode shop = new TreeNode();
                    Shop s = shops.First(x => x.ID == item);
                    var issues = list.Where(x => x.ShopID == item).OrderBy(x => x.Name).ToList();

                    shop.Text = string.Format("{0} ({1})", s.Name, issues.Count);
                    shop.ImageIndex = 0;
                    shop.SelectedImageIndex = 0;
                    //shop.Tag = item;
                    foreach (var t in issues)
                    {
                        shop.Nodes.Add(GetTreeNode(t));
                    }

                    nodes.Add(shop);
                }
            }
            else
            {
                foreach (var item in list)
                {
                    nodes.Add(GetTreeNode(item));
                }
            }
            return nodes;
        }

        private TreeNode GetTreeNode(Issue item)
        {
            TreeNode node = new TreeNode();
            node.Text = item.DisplayText;
            node.ImageIndex = (int)item.Priority;
            node.SelectedImageIndex = (int)item.Priority;
            node.Tag = item;
            //if (t.Priority != Priority.Low && (t.Status == Status.New || t.Status == Status.Open || t.Status == Status.InProgress))
            //issue.BackColor = System.Drawing.ColorTranslator.FromHtml(t.Priority.GetColor());
            node.ContextMenuStrip = contextMenuStrip1;

            return node;
        }

        private void btnBack_Click(object sender, EventArgs e)
        {

        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            ShowIssueDetailsForm(currentItem);
        }

        public void ShowIssueDetailsForm(Issue item)
        {
            Cursor.Current = Cursors.WaitCursor;
            //issueDetails issue = new issueDetails(currentItem);
            //issue.Dock = DockStyle.Fill;
            //PopUp p = new PopUp();
            //p.Text = currentItem.DisplayText;
            //p.Controls.Clear();
            //p.Controls.Add(issue);
            //p.Show();
            objMain.LoadIssueDetails(item);

            Cursor.Current = Cursors.Default;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            panelBody.Controls.Clear();
            search_result obj = new search_result(txtSearchBox.Text, doFilter);
            obj.iList = this;
            obj.Dock = DockStyle.Fill;
            panelBody.Controls.Add(obj);

            lblItemCount2.Visible = false;
            cmbItemPerPage.Visible = false;
            Cursor.Current = Cursors.Default;
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Title = "Please choose location where report will be saved.";
            saveFileDialog1.Filter = "CSV | *.csv";
            DialogResult dl = saveFileDialog1.ShowDialog();
            if (dl == DialogResult.OK)
            {
                //string fileName = "IssueTracker_Report_" + DateTime.Now.Ticks.ToString() + ".csv";
                string filePath = saveFileDialog1.FileName;
                StringBuilder strB = new StringBuilder();
                strB.Append("Shop Name, Issue ID, Issue Name, Description, Priority, Status, Date From , Date To, Data");
                strB.AppendLine();
                foreach (var item in result)
                {
                    strB.Append(string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}",
                       Utility.PolishData(item.ShopName), item.ID, Utility.PolishData(item.Name), Utility.PolishData(item.Description), item.Priority.ToString(), item.Status.ToString(), item.DateStart.ToString(), item.DateEnd.ToString(), item.UDF1));
                    strB.AppendLine();
                }
                try
                {
                    System.IO.File.WriteAllText(filePath, strB.ToString());
                    MessageBox.Show("Data has been successfully saved to following location.\n" + filePath, "Export successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    ErrorLogger.WriteLog("Export to file", ex);
                    throw;
                }
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowIssueDetailsForm(currentItem);
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag is Issue)
                currentItem = (Issue)e.Node.Tag;
        }

        private void cmbItemPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            LoadIssuesPage();
            Cursor.Current = Cursors.Default;
        }

        private void treeViewOpenIssues_DoubleClick(object sender, EventArgs e)
        {
            TreeView tr = (TreeView)sender;
            TreeNode no = tr.SelectedNode;
            if (no != null && no.Tag is Issue)
            {
                currentItem = (Issue)no.Tag;
                ShowIssueDetailsForm(currentItem);
            }
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            Filter objFilter = new Filter();
            objFilter.iList = this;
            int x = objMain.Location.X + btnFilter.Location.X + 130;
            int y = objMain.Location.Y + btnFilter.Location.Y + 55;
            objFilter.Location = new Point(x, y);
            objFilter.ShowDialog();
        }

        public void SetFilterBGImage(bool filtered)
        {
            if (filtered)
                btnFilter.BackgroundImage = Properties.Resources.Filter1;
            else
                btnFilter.BackgroundImage = Properties.Resources.Filter0;
        }

        public void SetCountValue(int count)
        {
            lblItemCount.Text = string.Format("Total {0} items found.", count);
        }

    }
}
